package org.ithasu.tools.bugOne;

import org.ithasu.tools.Console;
import org.ithasu.tools.IOTools;
import org.ithasu.tools.bugOne.BugOneSniffer.BugOneAdapter;
import org.ithasu.tools.bugOne.SerialSniffer.MessageListener;

public class BugOneTester {

	public static void main(String[] args) {
		SerialSniffer s = new SerialSniffer();
		if (!s.connect("/dev/ttyUSB0", 19200)) {
			Console.error("Failed to connect");
		} else {
			Console.message("Connected at " + s.getSerialPort().getBaudRate());
		}

		final BugOneSniffer b = new BugOneSniffer(s, (byte) 0x1A);
		b.addMessageListener(new MessageListener() {
			@Override
			public void onMessageReceived(SerialSniffer sniffer, byte[] message) {
				Console.message("-- Message was not handled --");
				System.out.println("Size: " + message.length);
				for (int i = 0; i < message.length; i++) {
					System.out.print(IOTools.toHexByte(message[i]));
					System.out.print(", ");
				}
				System.out.println();
			}
		});

		b.addBugOneListener(new BugOneAdapter() {
			@Override
			public void onPongEvent(byte srcNodeId) {
				Console.message("Received a response from node: "
						+ IOTools.toHexByte(srcNodeId));
			}
		});

		// for (int i = 0; i < 256; i++) {
		// Console.message("Ping " + IOTools.toHexByte(i) + " ...");
		// b.ping((byte) i);
		// try {
		// Thread.sleep(150);
		// } catch (Throwable e) {
		// }
		// }

		b.addBugOneListener(new BugOneAdapter() {
			@Override
			public void onInputEvent(byte srcNodeId, byte srcDeviceId,
					byte destDeviceId, Object value) {
				Console.message(Integer.toHexString(srcNodeId) + "."
						+ Integer.toHexString(srcDeviceId) + " = "
						+ String.valueOf(value));
			}
		});

		//		int i = 0;
		//		while (true) {
		//			b.set((byte) 0x17, (byte) 0x0, (byte) 0x2, i++ % 2);
		//			try {
		//				Thread.sleep(1000);
		//			} catch (Throwable e) {
		//			}
		//		}

	}

}
